package com.kgc.controller;

import com.kgc.annotation.CheckPermission;
import com.kgc.entity.Address;
import com.kgc.service.AddressService;
import com.kgc.util.ResultAjax;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author :qinya
 * @PackageName:com.kgc.controller
 * @ClassName: AddressController
 * @Description: TODO
 * @date : 2025/5/20,21:10
 */
@RestController
@RequestMapping("/address")
public class AddressController {

    @Autowired
    private AddressService addressService;
//    @Autowired
//    private RedisTemplate redisTemplate;

    @GetMapping("/page")
    @CheckPermission({"1", "0"})
    public ResultAjax queryByPage(@RequestParam Map<String, String> params) {
        Map<String, Object> map = new HashMap<>();
        map.put("pageNum", Integer.parseInt(params.get("pageNum")));
        map.put("pageSize", Integer.parseInt(params.get("pageSize")));
        map.put("userId", Integer.parseInt(params.get("uid")));
        return ResultAjax.success().add("pageInfo", addressService.selectByPage(map));
    }

    @PostMapping("/add")
    @CheckPermission({"1", "0"})
    public ResultAjax addAddress(@RequestBody Address address) {
        address.setCreateTime(new Date());
        return ResultAjax.success().add("addStatus", addressService.addAddress(address));
    }

    @PostMapping("/edit")
    @CheckPermission({"1", "0"})
    public ResultAjax editAddress(@RequestBody Address address) {
        System.out.println("address中的address" + address.getAddress());
        return ResultAjax.success().add("editStatus", addressService.editAddress(address));
    }

    @GetMapping("/del/{id}")
    @CheckPermission({"1", "0"})
    public ResultAjax delAddress(@PathVariable("id") int id) {
        return ResultAjax.success().add("delStatus", addressService.delAddress(id));
    }

    @GetMapping("/find/{id}")
    @CheckPermission({"1", "0"})
    public ResultAjax findAddress(@PathVariable("id") int id) {
        return ResultAjax.success().add("address", addressService.selectById(id));
    }


    @GetMapping("/change")
    @CheckPermission({"1", "0"})
    public ResultAjax setDefaultAddress(String currentDefaultId, String newDefaultId) {
        boolean temp = true;
        if (!StringUtils.isEmpty(currentDefaultId)) {
            temp = addressService.cancelDefaultAddress(Integer.parseInt(currentDefaultId));
        }
        if (!StringUtils.isEmpty(newDefaultId)) {
            temp = addressService.setDefaultAddress(Integer.parseInt(newDefaultId));
        }
        return ResultAjax.success().add("changeStatus", temp);
    }

}
